<template>
  <TreeItemList
    :data="value"
    label="表格字段"
    :supportSort="true"
    :nodeAllowDrop="nodeAllowDrop"
    @add="onEditTableColumn()"
    @edit="onEditTableColumn"
    @delete="onRemoveTableColumn"
    @update:data="onValueChange"
    @dragEnd="onDragEnd"
    :prop="{
      label: 'showName',
      value: 'columnId',
    }"
  >
    <template v-slot="scope">
      <div>
        <span>{{ scope.data.showName }}</span>
        <el-tag
          size="mini"
          :type="scope.data.isGroup ? 'warning' : 'success'"
          style="margin-left: 8px"
        >
          {{ scope.data.isGroup ? '分组' : '数据' }}
        </el-tag>
      </div>
    </template>
  </TreeItemList>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import { findTreeNode } from '@/common/utils';
import TreeItemList from '@/components/TreeItemList/index.vue';
import { ANY_OBJECT } from '@/types/generic';
import { Dialog } from '@/components/Dialog';
import { SysOnlineFormType } from '@/common/staticDict';
import { useLayoutStore } from '@/store';
import EditOnlineTableColumn from './editOnlineTableColumn.vue';

const props = defineProps<{ value: ANY_OBJECT[] }>();
const layoutStore = useLayoutStore();
const formConfig = inject('formConfig', () => {
  console.error('OnlineTableColumnSetting: formConfig not injected');
  return {} as ANY_OBJECT;
});

const emit = defineEmits<{ 'update:value': [ANY_OBJECT[]] }>();

const getGroupColumnList = computed(() => {
  return props.value.filter(item => item.isGroup);
});

const onValueChange = (value: ANY_OBJECT[]) => {
  emit('update:value', value);
};

const getParentNode = (node, tree) => {
  if (node == null || node.parentId == null) return null;
  return findTreeNode(tree || props.value || [], node.parentId, 'columnId');
};

const handlerEditOperate = (row: ANY_OBJECT | null, res: ANY_OBJECT) => {
  let tempList = JSON.parse(JSON.stringify(props.value || []));
  let parentNode = getParentNode(res, tempList);
  if (res.isGroup && res.columnId == null) res.columnId = new Date().getTime() + '_column';
  if (row == null) {
    if (parentNode) {
      parentNode.children = parentNode.children || [];
      parentNode.children.push(res);
    } else {
      tempList.push(res);
    }
  } else {
    let oldParentNode = getParentNode(row, tempList);
    // 如果父节点改变了，从旧的父节点中删除编辑节点
    if (row.parentId !== res.parentId) {
      if (oldParentNode) {
        oldParentNode.children = (oldParentNode.children || []).filter(
          item => item.columnId !== row.columnId,
        );
      } else {
        tempList = tempList.filter(item => item.columnId !== row.columnId);
      }
      // 将编辑节点添加到新的父节点中
      if (parentNode != null) {
        parentNode.children = parentNode.children || [];
        parentNode.children.push(res);
      } else {
        tempList.push(res);
      }
    } else {
      let childrenList = parentNode ? parentNode.children : tempList;
      childrenList = (childrenList || []).map(item => {
        if (res.fieldType === 0) {
          return item.columnId === res.columnId ? res : item;
        } else {
          return item.id === res.id ? res : item;
        }
      });
      if (parentNode) {
        parentNode.children = childrenList;
      } else {
        tempList = childrenList;
      }
    }
  }
  onValueChange(tempList);
};
const onEditTableColumn = (row: ANY_OBJECT | null = null) => {
  let tableList = formConfig().getTableWidgetTableList;
  // 非查询页面只能从组件绑定的表中选择
  if (
    formConfig().currentWidget.isTableExpand ||
    (formConfig().form.formType !== SysOnlineFormType.QUERY &&
      formConfig().form.formType !== SysOnlineFormType.ADVANCE_QUERY &&
      formConfig().form.formType !== SysOnlineFormType.GROUP_QUERY)
  ) {
    tableList = (tableList || []).filter((table: ANY_OBJECT) => {
      return table.tableId === formConfig().currentWidget.bindData.tableId;
    });
  }
  Dialog.show<ANY_OBJECT>(
    row ? '编辑字段' : '添加字段',
    EditOnlineTableColumn,
    {
      area: '600px',
    },
    {
      rowData: row,
      tableList: tableList,
      usedColumnList: props.value.map(item => item.columnId),
      formConfig: formConfig(),
      supportGroup: formConfig().form.formType !== SysOnlineFormType.WORK_ORDER,
      groupColumnList: getGroupColumnList.value,
    },
  )
    .then(res => {
      handlerEditOperate(row, res);
    })
    .catch(e => {
      console.warn(e);
    });
};
const onRemoveTableColumn = (row: ANY_OBJECT) => {
  ElMessageBox.confirm('是否删除此表格列？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let parentNode = getParentNode(row);
      let childrenList = parentNode ? parentNode.children : props.value;
      childrenList = (childrenList || []).filter(item => item.columnId !== row.columnId);
      if (parentNode) {
        parentNode.children = childrenList;
      }
      let tempList = parentNode ? props.value : childrenList;
      tempList = JSON.parse(JSON.stringify(tempList || []));
      onValueChange(tempList);
    })
    .catch(e => {
      console.warn(e);
    });
};

const nodeAllowDrop = (draggingNode, dropNode, type) => {
  if (type === 'inner') {
    return dropNode.data.isGroup;
  }
  return true;
};

const onDragEnd = (draggingNode, dropNode, dropType) => {
  if (dropType === 'inner') {
    draggingNode.data.parentId = dropNode.data.columnId;
  } else {
    draggingNode.data.parentId = dropNode.data.parentId;
  }
  onValueChange(JSON.parse(JSON.stringify(props.value || [])));
};
</script>
